import json
import sys

import facade
import pymysql
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")


class DownSubject(object):

    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutil = facade.MysqlUtiles(configfile, "db", logger=self.logger)
        self.header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Host": "user.bookan.com.cn",
            "Pragma": "no-cache",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
        }

    def task(self):
        sql = "select url,subjid from subject where stat=0 and failcount<3"
        rows = self.mysqlutil.SelectFromDB(sql)
        for row in rows:
            categoryId = row[1]
            totalNum = self.down_allnum(categoryId)
            # 开始翻页
            for i in range(1, (int(totalNum) - 1) // 20 + 2):
                self.down_para_journal(categoryId, i)
            sql = "update `subject` set stat=1 where  subjid = '{}'".format(categoryId)
            self.mysqlutil.ExeSqlToDB(sql)

    def down_allnum(self, categoryId):
        url = "http://user.bookan.com.cn/index.php?op=Resource.categoryIssuesCount&instanceId=23579&resourceType=1&categoryId={}".format(
            categoryId)
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      endstring="",
                                                      headers=self.header,
                                                      timeout=(30, 60),
                                                      mark="status")
        if BoolResult:
            jsondicts = json.loads(r.text)
            print(jsondicts)
            # 该分类下的总量
            totalNum = jsondicts['data']["totalNum"]
            return totalNum
        else:
            print("下载错误,请检查")
            sys.exit(-1)

    def down_para_journal(self, categoryId, pagenum):
        url = "http://user.bookan.com.cn/index.php?op=Resource.categoryIssues&instanceId=23579&resourceType=1&categoryId={}&pageNum={}&limitNum=20".format(
            categoryId, pagenum)
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      endstring="",
                                                      headers=self.header,
                                                      timeout=(30, 60),
                                                      mark="status")
        if BoolResult:
            jsondicts = json.loads(r.text)
            data = jsondicts["data"]
            for onedata in data:
                id = onedata["resourceId"]
                resourceName = pymysql.escape_string(onedata["resourceName"])
                issueId = onedata["issueId"]
                subjid = categoryId
                jpg = onedata["webp"]
                imageurl = "http://img1-qn.bookan.com.cn/page{jpg}/{id}/{id}-{issueId}/cover_small.mg".format(jpg=jpg,
                                                                                                              id=id,
                                                                                                              issueId=issueId)
                sql = "replace into journal(jid,qkname,issueId,subjid,cover) values ('%s','%s','%s','%s','%s')"
                sql = sql % (id, resourceName, issueId, subjid, imageurl)
                self.mysqlutil.ExeSqlToDB(sql)
        else:
            print("下载失败")
            sys.exit(-1)


def main():
    down = DownSubject()
    down.task()


if __name__ == "__main__":
    main()
